﻿using AutoMapper;
using CSRedis;
using Microsoft.EntityFrameworkCore;
using SmartConference.Api.Applocations.IServices;
using SmartConference.Api.DTO;
using SmartConference.Api.Filter;
using SmartConference.Domain;
using SmartConference.ErrorCode;
using SmartConference.Infrastructure.Interfaces;
using System.ComponentModel;
using System.Text.Json;

namespace SmartConference.Api.Applocations.Services
{
    public class MeetingRoomServices : IMeetingRoomServices
    {
        private readonly IMeetingRoomRepository meetRep;
        private readonly IMeetingAppointRepository meetingAppointRepository;
        private readonly CSRedisClient redis;
        private readonly RedisHelp<MeetingRoom> helper;
        private readonly IMapper mapper;

        public MeetingRoomServices(IMeetingRoomRepository meetRep,IMeetingAppointRepository meetingAppointRepository,CSRedisClient redis, RedisHelp<MeetingRoom> helper,IMapper mapper)
        {
            this.meetRep = meetRep;
            this.meetingAppointRepository = meetingAppointRepository;
            this.redis = redis;
            this.helper = helper;
            this.mapper = mapper;
        }

        public async Task<ApiResult> AddMeetRoom(AddMeetingRoomDTO meetingRoom)
        {
            try
            {
                var roomlist = await meetRep.GetAsync(x => x.RoomName == meetingRoom.RoomName);
                if (roomlist != null)
                {
                    return ApiResult.Error(ApiResultCode.Error, "会议室已存在");
                }
                var newlist=mapper.Map(meetingRoom, new MeetingRoom());
                await meetRep.AddAsync(newlist);
                return ApiResult.Success(ApiResultCode.Success);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<ApiResult<int>> BatchDeleteRoom(int[]  ids)
        {
            try
            {
                //计数
                var i = 0;
                //遍历数组
                foreach (var item in ids)
                {
                    //获取需要删除的会议室id
                    var roomid = Convert.ToInt32(item);
                    //查当前会议室是否被预约
                    var meetlist = await meetingAppointRepository.GetAsync(x => x.MeetingRoomID == roomid);
                    //已预约异常
                    if (meetlist != null)
                    {
                        return ApiResult<int>.Error(ApiResultCode.Error, "该会议室有预约记录，无法删除");
                    }
                    //未预约删除
                    var roomlist = await meetRep.GetAsync(x => x.Id == roomid);
                    await meetRep.DeleteAsync(roomlist);
                    i++;
                }
                return ApiResult<int>.Success(ApiResultCode.Success,i);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<ApiResult> DeleteMeetRoom(int Id)
        {
            try
            {
                //查当前会议室是否被预约
                var meetlist = await meetingAppointRepository.GetAsync(x => x.MeetingRoomID == Id);
                //已预约异常
                if (meetlist != null)
                {
                    return ApiResult<int>.Error(ApiResultCode.Error, "该会议室有预约记录，无法删除");
                }
                var roomlist=await meetRep.GetAsync(x => x.Id == Id);
                await meetRep.DeleteAsync(roomlist);
                return ApiResult.Success(ApiResultCode.Success);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<ApiResult<IList<MeetingRoom>>> GetMeetRoom()
        {
            try
            {
                ////定义Redis缓存键
                //string rediskey = "MeetingRoomList";
                ////尝试从redis中获取缓存数据
                //var cacheData=await redis.GetAsync(rediskey);
                //if (!string.IsNullOrEmpty(cacheData))
                //{
                //    var newlist= JsonSerializer.Deserialize<List<MeetingRoom>>(cacheData);
                //    if (newlist != null)
                //    {
                //        return ApiResult<IList<MeetingRoom>>.Success(ApiResultCode.Success, newlist);
                //    }
                //}
                ////缓存中没有数据，则从数据库中获取数据
                //var roomlist = meetRep.GetAll();
                //await  redis.SetAsync("MeetingRoomList", JsonSerializer.Serialize(roomlist),60*60);
                //return ApiResult<IList<MeetingRoom>>.Success(ApiResultCode.Success, roomlist.ToList());
                IList<MeetingRoom> list = await helper.GetRedisList("MeetingRoomList", async () =>
                {
                    var roomlist = await meetRep.GetAll().ToListAsync();
                    return roomlist;
                }, 60 * 60);
                return ApiResult<IList<MeetingRoom>>.Success(ApiResultCode.Success, list);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<ApiResult<ApiPaging<MeetingRoom>>> ShowMeetRoom(string? RoomName, [DefaultValue(1)] int pageIndex, [DefaultValue(10)] int pageSize)
        {
            try
            {
                var roomlist= meetRep.GetAll();
                if (!string.IsNullOrEmpty(RoomName))
                {
                    roomlist = roomlist.Where(x => x.RoomName.Contains(RoomName));
                }
                int totalcount = roomlist.Count();
                int pagecount = (int)(Math.Ceiling(totalcount * 1.0 / pageSize));
                roomlist = roomlist.OrderBy(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                ApiPaging<MeetingRoom> paging = new ApiPaging<MeetingRoom>(totalcount, pagecount, roomlist.ToList());
                return ApiResult<ApiPaging<MeetingRoom>>.Success(ApiResultCode.Success, paging);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<ApiResult> UpdateMeetRoom(MeetingRoom meetingRoom)
        {
            var roomlist=await meetRep.GetAsync(x => x.Id != meetingRoom.Id&&x.RoomName==meetingRoom.RoomName&&!x.IsDelete);
            if (roomlist != null)
            {
                return ApiResult.Error(ApiResultCode.Error, "会议室已存在");
            }
            await meetRep.UpdateAsync(meetingRoom);
            return ApiResult.Success(ApiResultCode.Success);
        }
    }
}
